#include "cworker.h"

#define CONFIG_PATH "./etc/cworker.cfg"

wtk_log_t *g_log = NULL;

cworker_cfg_t * parse_cfg() {
    cworker_cfg_t *cfg = NULL;

    wtk_main_cfg_t *maincfg = wtk_main_cfg_new_type(cworker_cfg, CONFIG_PATH);
    if (!maincfg) {
        wtk_debug(" init config %s failed\n", CONFIG_PATH);
    } else {
        cfg = (cworker_cfg_t *)maincfg->cfg;
    }

    return cfg;
}

void init_logger(wtk_log_cfg_t *cfg) {
    char *logpath = wtk_string_to_str(&(cfg->fn));
	g_log = wtk_log_new3(logpath, cfg->level, cfg->daily);
}

void run_loop() {
    cJSON *data = NULL;

    while (1) {
        //log_i("begin pop lst: %s", "lst");
        data = cworker_redis_blpop("lst", 0);

        if (data) {
            log_i("key: %s, value: %s", "lst", cJSON_PrintUnformatted(data));

            // #TODO: 把redis里的数据，转成调用内核
            //cworker_exec(&(cfg->scripts.train_patslot_product));

            cJSON_Delete(data);
        }

        wtk_msleep(100);
    }
}

int main(int argc, char **argv) {
    int ret = -1;

    cworker_cfg_t *cfg = parse_cfg();
    if (cfg) {
        init_logger(&(cfg->log));

        ret = cworker_redis_init(&(cfg->redis));
        if (ret == 0)  {
            run_loop();
            log_i("Exit normally. ret: %d", ret);

            cworker_redis_finit();
        }

        if (g_log) wtk_log_delete(g_log);
    }

    return ret;
}
